package leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description T692 前K个高频单词
 * @Author away
 * @Version V1.0.0
 * @Since 1.0
 * @Date 21.5.20
 */

public class T692 {

    public static void main(String[] args) {
        T692 t692 = new T692();
//        String[] words = {"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"};
        String[] words = {"i", "love", "leetcode", "i", "love", "coding"};
        int k = 4;

        List<String> strings = t692.topKFrequent(words, k);
        System.out.println(strings);
    }

    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> map = new HashMap();
        for(int i = 0 ;i< words.length;i++){
            String key = words[i];
            map.put(key, (map.getOrDefault(key, 0)+1));
        }
        //先按值倒叙再按key升序
        List<String> collect = map.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue).reversed().thenComparing(Map.Entry::getKey))
                .limit(k)
                .map(Map.Entry<String, Integer>::getKey)
                .collect(Collectors.toList());

        return collect;

    }
}
